// detail.js
var app = getApp();
var QR = require("../../../common/qrcode.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    drivermap: '',
    mapmarks: '',
    line: '',
    controls: '',
    placeholder: 'http://www.hn96520.com/',
    disabled: false,
    isTrue: true,
    payColor: '#00a0e9',
    appColor: app.appColor
  },
  
  // 提示框定时器
  hintTime: function (that) {
    let num = 2;
    const time = setInterval(function () {
      if (num <= 0) {
        that.setData({ hint: false });
        return;
      }
      num--;
    }, 1000)
  },
  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    try{
      app.showLoadings();
      let that = this;
      if (options.distance){
        this.setData({
          endplace: options.endplace,
          orderstatus: options.orderstatus,
          distance: options.distance
        });
      }else{
        wx.getStorage({
          key: 'cusOrderCode',
          success: function (res) {
            that.message(res.data);
            that.setData({distance: res.data})
          }
        })
      }
    } catch(err){}
  },
  //适配不同屏幕大小的canvas
  setCanvasSize: function () {
    var size = {};
    try {
      var res = wx.getSystemInfoSync();
      var scale = 150 / 75;
      var width = res.windowWidth / scale;
      var height = width;
      size.w = width;
      size.h = height;
    } catch (e) {
      console.log("获取设备信息失败" + e);
    }
    return size;
  },
  createQrCode: function (url, canvasId, cavW, cavH) {
    QR.qrApi.draw(this.data.distance, canvasId, cavW, cavH);
  },
  onReady: function () {
    var size = this.setCanvasSize();
    var initUrl = this.data.placeholder;
    this.createQrCode(this.data.distance, "mycanvas", size.w, size.h);
  },

  qrcode: function (code) {
    var that = this;
    var st = setTimeout(function () {
      wx.hideToast()
      var size = that.setCanvasSize();
      //绘制二维码
      that.createQrCode(code, "mycanvas", size.w, size.h);
      clearTimeout(st);
    }, 500)
  },

  // 位置信息
  location: function (e) {
    var stand = e.currentTarget.dataset.stand,
      location = e.currentTarget.dataset.location.split(',');

    wx.openLocation({
      latitude: parseFloat(location[1]),
      longitude: parseFloat(location[0]),
      scale: 14,
      name: stand,
    })
  },
  checkOpenToast: function (message) {
    wx.showToast({
      title: message,
      icon: 'success_no_circle',
      duration: 10000
    });
  },
  scanQRcode: function(e){
    let that = this;
    wx.scanCode({
      success: (res) => {
        wx.request({
          url: '171.8.76.2:6087/CheckTicketByPassenger',
          header: {
            Authorization: "Bearer " + app.accesstoken
          },
          data: {
            OrderCode: that.data.distance,
            BusInfo: res.result
           },
          dataType: 'json',
          success: function (res) {
            if(res.data.result){
              that.checkOpenToast('检票成功');
            }
          },
          fail: function (err) {
            try{
              that.checkOpenToast(res.Message);
            }catch(err){}
          }
        })
      }
    })
  },
  // 订单详情  
  message: function (orderCode) {
    var that = this;
    wx.request({
      url: app.serviceurl + 'CustomLine/CustomGetOrderDetail',
      header: {
        Authorization: "Bearer " + app.accesstoken
      },
      data: { OrderCode: this.data.distance ? this.data.distance : orderCode },
      dataType: 'json',
      success: function (res) {
        if (res.data.Result) {
          // 司机信息
          if (res.data.Result == true) {
            app.DriverName = res.data.DriverName;
            app.DriverPhone = res.data.DriverPhone;
            app.PlateNumber = res.data.PlateNumber;
            app.OrderCode = res.data.OrderMain.OrderCode;

            var time = res.data.OrderMain.StartDate.substring(6, 19),
              d = new Date(parseInt(time)),
              m = (d.getMonth() + 1) < 10 ? '0' + (d.getMonth() + 1) : (d.getMonth() + 1),
              day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate(),
              date = d.getFullYear() + '-' + m + '-' + day;
            if (res.data.TakeManList != null && typeof (res.data.TakeManList) != undefined) {
              res.data.TakeManList.forEach(function (item) {
                item.cardid = item.cardid.replace(/(\d{6})\d{4}(\d{4})/, '$1****$2');
              });
            }
          }
          if (res.data.Heading == "" || res.data.Heading == null) {
            res.data.Heading = "../../../pages/image/photo.jpg"
          }
          that.setData({
            message: res.data.OrderMain,
            rider: res.data.TakeManList,
            OrderCode: res.data.OrderMain.OrderCode,
            ref: res.data,
            date: date,
            phone: app.HandsetNumber,
            reason: res.data.CannotRefundReason
          });

          app.hideLoadings();
        } else {
          that.setData({
            date: date,
            ref: res.data
          })
          app.hideLoadings();
          return
        }

      },
      fail: function (res) {
        console.log(res)
      }
    })
  },

  // 跳转到二维码页面
  QRcodes: function () {
    wx.navigateTo({
      url: '../../../pages/QRcode/QRcode?code=' + this.data.distance,
    })
  },

  // 取消订单
  abandon: function () {
    var that = this;
    wx.showModal({
      title: '确认取消',
      content: '确定取消该订单吗？',
      confirmText: "确定",
      cancelText: "放弃",
      success: function (res) {
        if (res.confirm) {
          app.hint = false;
          that.setData({ isTrue: false })
          wx.request({
            url: app.serviceurl + 'CustomLine/CustomCancleOrder',
            header: {
              Authorization: "Bearer " + app.accesstoken
            },
            data: { OrderCode: that.data.distance },
            dataType: 'json',
            success: function (res) {
              if (!res.data.Result) {
                wx.showModal({
                  title: "取消订单失败",
                  content: res.data.Message,
                  showCancel: false,
                  confirmText: "确定",
                  success: function (res) { }
                })
                return
              }
              that.message();
              that.setData({ isTrue: true })
            },
            fail: function (res) {
              console.log(res)
              that.setData({ isTrue: true })
            },
            complete: function (res) {
              that.setData({
                // hintMessage: res.data.Message,
                hint: true
              })
              that.hintTime(that);
            }
          })
        }
      }

    });
  },
  openToast: function () {
    wx.showToast({
      title: '支付完成',
      icon: 'success',
      duration: 600
    });
  },
  // 支付
  wxpay: function (e) {
    this.setData({
      disabled: true,
      payColor: '#1BB166'
    })
    var that = this;
    wx.request({
      url: app.serviceurl + 'CustomLine/CustomPayOrder',
      header: {
        Authorization: "Bearer " + app.accesstoken
      },
      data: { OrderCode: that.data.OrderCode },
      success: function (res) {
        if (res.data.Result) {
          wx.requestPayment({
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            package: res.data.package,
            signType: res.data.signType,
            paySign: res.data.paySign,
            success: function (resr) {
              if (resr.errMsg == "requestPayment:ok") {
                //支付成功
                that.openToast();
                that.message();
                app.hint = false;
                app.orderState = '已付款';
                var orderId = e.currentTarget.dataset.indent;
                app.orderId = orderId;
              }
            }
          })
        }
        else {
          wx.showToast({
            title: '调起支付失败',
          })
        }
      },
      fail: function (error) {
        console.log(error);
      },
      complete: function () {
        var time = setTimeout(function () {
          that.setData({
            disabled: false,
            payColor: '#1BB166'
          });
        }, 1000)
      }
    });
  },


  phone: function (e) {
    var that = this;
    wx.makePhoneCall({
      phoneNumber: that.data.ref.DriverPhone
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    if (wx.getScreenBrightness) {
      wx.getScreenBrightness({
        success: function (res) {
          that.setData({
            initLuminance: res.value
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 获取订单信息
    this.message();
      // 调用二维码绘制函数
    this.qrcode(this.data.distance);
    if (wx.setScreenBrightness) {
      wx.setScreenBrightness({
        value: this.data.initLuminance,
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  position: function (e) {
    wx.navigateTo({
      url: '../lookdriverposition/lookdriverposition?name=' + this.data.ref.DriverName + '&ordercode=' + this.data.distance,
    })
  },
  openConfirm: function () {
    wx.navigateTo({
      url: '../../../pages/refund/refund?code=' + this.data.distance,
    })
  },
  refundreson: function () {
    wx.showModal({
      content: this.data.reason,
      showCancel: false,
      success: function (res) {
        if (res.confirm) {}
      }
    });
  }
})